#! /bin/bash
# ----------------------------------------------------------------------
# file: codeformat.sh
# author: keefe, wuqifu@gmail.com
# date: 2016/5/8, 2017/10/15
# ----------------------------------------------------------------------

DIR=$1
LANGS_REGEX='.*\.\(c\|h\|cpp\|py\|php\)' 

general_format()
{
    echo 'Doing general_format'
    # remove line end space, 去除行尾空格
    #find $DIR -iname "*.py"  |xargs sed -i 's/\s\+$//g'
    #find $DIR -regex '.*\.\(c\|h\|min\|cpp\|py\|php\)'  | xargs wc -l
    find $DIR -regex $LANGS_REGEX  | xargs wc -l

    # change sh fileformat: dos2unix
    # dos format file to unix us: "\r\n"-->"\n"
    find $DIR -iname "*.sh" | grep -v $0 |xargs dos2unix

    # stat codeline: remove space line
    #find $DIR -name "*.py" |xargs cat |grep -v ^$ |wc -l
    #find $DIR -regex '.*\.\(c\|h\|min\|cpp\|py\|php\)'  | xargs wc -l

}

langs_format()
{
    echo 'Doing langs_format'
    #PYTHON_FORMAT_TOOL="$(which autopep8)"
    FORMAT_TOOL="$(which astyle)"
    PYTHON_FORMAT_TOOL="autopep8 -i"

    # python
    find -iname "*.py" |xargs $PYTHON_FORMAT_TOOL

    # c/c++/java
    find -iname "*.c" |xargs $FORMAT_TOOL
    find -iname "*.cpp" |xargs $FORMAT_TOOL
    find -iname "*.java" |xargs $FORMAT_TOOL
}

clean_file()
{
    echo 'Doing clean_file'
    # clean middle file: *.orig generated by astyle
    find -iname "*.orig" |xargs rm

    # langs obj
    find -iname "*.pyc" |xargs rm
    find -iname "*.class" |xargs rm
    find -iname "*.o" |xargs rm
}

echo -e 'START codeformat\n'
# call functions
general_format
#langs_format
#clean_file

echo -e '\nEND codeformat\n'
